﻿using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using Caramel.Linq;

namespace Caramel.Web.Mvc.Validation
{
	public class ModelValidatorConventionContainer
	{
		public ModelValidatorConventionContainer(AutoModelValidatorContainer container)
		{
			this.Container = container;
			this.Conventions = new List<IModelValidatorConvention>();
		}

		internal IList<IModelValidatorConvention> Conventions { get; set; }

		public AutoModelValidatorContainer Container { get; set; }

		public AutoModelValidatorContainer Add<T>() where T : IModelValidatorConvention
		{
			this.Conventions.Add(Activator.CreateInstance<T>() as IModelValidatorConvention);

			return this.Container;
		}

		//public ConventionContainer Add(Type type)
		//{
		//    _types.Add(type);

		//    return this;
		//}

		public AutoModelValidatorContainer AddFromAssemblyOf<T>()
		{
			return this.AddFromAssembly(typeof(T).Assembly);
		}

		public AutoModelValidatorContainer AddFromAssembly(Assembly assembly)
		{
			assembly.
				GetExportedTypes().
				Where(t => typeof(IModelValidatorConvention).IsAssignableFrom(t)).
				Where(t => !t.IsAbstract).
				Select(t => Activator.CreateInstance(t) as IModelValidatorConvention).
				Each(c => this.Conventions.Add(c));

			return this.Container;
		}
	}
}
